import { PayloadAction, createSlice } from '@reduxjs/toolkit'
import { TokenState } from './StoreTokenSchema'

const initialState: TokenState = {
  accessToken: document.cookie.includes('accessToken=')
    ? document.cookie.replace(/(?:(?:^|.*;\s*)accessToken\s*=\s*([^;]*).*$)|^.*$/, '$1')
    : null,
  expireToken: document.cookie.includes('expireToken=')
    ? +document.cookie.replace(/(?:(?:^|.*;\s*)expireToken\s*=\s*([^;]*).*$)|^.*$/, '$1')
    : null,
  refreshToken: document.cookie.includes('refreshToken=')
    ? document.cookie.replace(/(?:(?:^|.*;\s*)refreshToken\s*=\s*([^;]*).*$)|^.*$/, '$1')
    : null,
}

const tokenSlice = createSlice({
  initialState,
  name: 'token',
  reducers: {
    clearTokens: () => {
      document.cookie = 'accessToken=; expires=Thu, 01 Jan 1970 00:00:00 UTC;'
      document.cookie = 'refreshToken=; expires=Thu, 01 Jan 1970 00:00:00 UTC;'
    },
    setTokens: (state, action: PayloadAction<TokenState>) => {
      state.accessToken = action.payload.accessToken
      document.cookie = `accessToken=${action.payload.accessToken}`
      state.refreshToken = action.payload.refreshToken
      document.cookie = `refreshToken=${action.payload.refreshToken}`
      state.expireToken = action.payload.expireToken
      document.cookie = `expireToken=${action.payload.expireToken}`
    },
  },
})

export const { clearTokens, setTokens } = tokenSlice.actions

export default tokenSlice.reducer
